package com.dn.lotte.ui.purchase.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.IdRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dn.lotte.R;
import com.dn.lotte.api.ServerApi;
import com.dn.lotte.bean.EventBusBean;
import com.dn.lotte.bean.PurchaseDetailNumberBean;
import com.dn.lotte.bean.PurchseDetailTimeBean;
import com.dn.lotte.bean.SelectNumberBean;
import com.dn.lotte.ui.purchase.adapter.NumberCAdapter;
import com.dn.lotte.utils.CommonUtils;
import com.easy.common.base.BaseActivity;
import com.easy.common.commonutils.SPUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.CustomPopWindow;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.common.commonwidget.RippleView;
import com.google.gson.Gson;
import com.lzy.okgo.model.HttpParams;
import com.xw.repo.BubbleSeekBar;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.dn.lotte.R.id.tv_data;

/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 * 确认投注
 *
 * @author DN
 * @data 2017/10/30
 **/
public class OKBettingActivity extends BaseActivity implements RippleView.OnRippleCompleteListener {

    @Bind(R.id.lt_main_title_left)
    TextView mLtMainTitleLeft;
    @Bind(R.id.lt_main_title)
    TextView mLtMainTitle;
    @Bind(R.id.lt_main_title_right)
    TextView mLtMainTitleRight;
    @Bind(R.id.toolbar)
    DnToolbar mToolbar;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(tv_data)
    TextView mTvData;
    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.selectDataRecyclerView)
    RecyclerView mSelectDataRecyclerView;
    @Bind(R.id.gameLinear)
    LinearLayout mGameLinear;
    @Bind(R.id.relative)
    RelativeLayout mRelative;
    @Bind(R.id.numberSelect)
    RippleView mNumberSelect;
    @Bind(R.id.numberAww)
    RippleView mNumberAww;
    @Bind(R.id.numberDelete)
    RippleView mNumberDelete;
    @Bind(R.id.betting)
    RippleView mBetting;
    @Bind(R.id.rlv_pursuenumber)
    RippleView rlvPursuenumber;

    private CustomPopWindow mHistoryPopup;

    private double amdString;// 基数 乘法算总价
    private int db = 1;//滑动监听
    private List<SelectNumberBean.NumberBean> mSelectNumberList;
    private NumberCAdapter mNumberCAdapter;
    private String mPoint;
    private List<SelectNumberBean.NumberBean> lastlist;
    private String mLid;

    @Override
    public int getLayoutId() {
        return R.layout.activity_okbetting;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        initTitle();
        mToolbar.setMainTitle("确认投注");
        mToolbar.setToolbarLeftBackImageRes(R.drawable.icon_back);
        mPoint = SPUtils.getSharedStringData(mContext, "POINT");

        Bundle extras = getIntent().getExtras();
        mLid = extras.getString("lid");
        String selectData = extras.getString("selectData");
        CommonUtils.setSelectNumberList(selectData);
        mSelectNumberList = CommonUtils.getSelectNumberList();
        mNumberDelete.setOnRippleCompleteListener(this);
        mNumberAww.setOnRippleCompleteListener(this);
        mBetting.setOnRippleCompleteListener(this);
        mNumberSelect.setOnRippleCompleteListener(this);
        rlvPursuenumber.setOnRippleCompleteListener(this);
        mSelectDataRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mNumberCAdapter = new NumberCAdapter(R.layout.item_select_number, mSelectNumberList);
        mSelectDataRecyclerView.setAdapter(mNumberCAdapter);

        mNumberCAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_delete:
                        mNumberCAdapter.remove(position);
                        CommonUtils.setSelectNumberList(new Gson().toJson(mSelectNumberList));
                        break;
                }

            }
        });
//        mNumberCAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
////                showHistoryDataPopup(view, mSelectNumberList.get(position));
//            }
//        });

        loadData();
    }

    private void loadData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("lid", mLid);
        ServerApi.getPurchaseDetailTime(httpParams)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PurchseDetailTimeBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
//                        mView.showLoading("");
                        startProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull PurchseDetailTimeBean timeBean) {
                        stopProgressDialog();
                        mTvTitle.setText(timeBean.getName());
                        mTvData.setText(timeBean.getNestsn());
                        String closetime = timeBean.getOrdertime();
                        int i = Integer.parseInt(closetime);
                        if (i == 0) {
                            mTvTime.setText("本期投注已经截止");
                        } else {
                            initTime(i * 1000);
                            restart(mTvTime);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }

    private CountDownTimer mTimer;

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        oncancel(mTvTime);
    }

    /**
     * 取消倒计时
     *
     * @param v
     */
    public void oncancel(View v) {
        if (mTimer != null) mTimer.cancel();
    }

    /**
     * 开始倒计时
     *
     * @param v
     */
    public void restart(View v) {
        if (mTimer != null) mTimer.start();
    }

    private void initTime(long l1) {
        //            mTvShow.setEnabled(true);
//            mTvShow.setText("获取验证码");
        mTimer = new CountDownTimer(l1, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mTvTime.setText((millisUntilFinished / 1000) + "秒");

            }

            @Override
            public void onFinish() {
//            mTvShow.setEnabled(true);
//            mTvShow.setText("获取验证码");
                mTvTime.setText("本期投注已经截止");
                loadData();
            }
        };
    }

    //历史popwindow
    private void showHistoryDataPopup(View view, SelectNumberBean.NumberBean numberBean) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.purchase_detail_foot, null);
        handleLogic(contentView, numberBean);
        mHistoryPopup = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setAnimationStyle(R.style.CustomPopWindowStyle)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.5f) // 控制亮度
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        CommonUtils.setSelectNumberList(new Gson().toJson(mSelectNumberList));
                        mNumberCAdapter.notifyDataSetChanged();
                    }
                })
                .create()
                .showAsDropDown(view, 0, 20);
    }

    private void handleLogic(View contentView, final SelectNumberBean.NumberBean numberBean) {
        BubbleSeekBar seekBar = (BubbleSeekBar) contentView.findViewById(R.id.seekbar);
        final TextView nowBounds = (TextView) contentView.findViewById(R.id.tv_now_bounds);
        final TextView mFD = (TextView) contentView.findViewById(R.id.tv_fd);
        final TextView mtvBuunds = (TextView) contentView.findViewById(R.id.tv_bounds);
        ImageButton addButton = (ImageButton) contentView.findViewById(R.id.add);
        ImageButton redButton = (ImageButton) contentView.findViewById(R.id.red);
        final TextView number = (TextView) contentView.findViewById(R.id.number);

        RadioGroup radioGroup = (RadioGroup) contentView.findViewById(R.id.group);
        RadioButton element = (RadioButton) contentView.findViewById(R.id.element);
        RadioButton angle = (RadioButton) contentView.findViewById(R.id.angle);
        RadioButton points = (RadioButton) contentView.findViewById(R.id.points);
        RadioButton deter = (RadioButton) contentView.findViewById(R.id.deter);

        double model = 0;
        String alltotal = numberBean.getAlltotal();
        switch (numberBean.getModel()) {
            case "元":
                element.setChecked(true);
                break;
            case "角":
                angle.setChecked(true);

                break;
            case "分":
                points.setChecked(true);
                break;
            case "厘":
                deter.setChecked(true);
                break;
        }

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.element:
                        numberBean.setModel("元");
                        numberBean.setAlltotal(CommonUtils.mul(1, Double.parseDouble(numberBean.getNum())) + "");
                        numberBean.setPrice(CommonUtils.mul(1, Double.parseDouble(numberBean.getNum())) + "");

                        double mulY = CommonUtils.mul(1, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulY, Double.parseDouble(numberBean.getTimes())) + "");
                        setNowBound(nowBounds,numberBean);
                        break;
                    case R.id.angle:
                        numberBean.setModel("角");
//                        numberBean.setAlltotal(CommonUtils.mul(0.1, Double.parseDouble(numberBean.getNum())) + "");
                        numberBean.setPrice(CommonUtils.mul(0.1, Double.parseDouble(numberBean.getNum())) + "");

                        double mulJ = CommonUtils.mul(0.1, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulJ, Double.parseDouble(numberBean.getTimes())) + "");
                        setNowBound(nowBounds,numberBean);
                        break;
                    case R.id.points:
                        numberBean.setModel("分");
//                        numberBean.setAlltotal(CommonUtils.mul(0.01, Double.parseDouble(numberBean.getNum())) + "");
                        numberBean.setPrice(CommonUtils.mul(0.01, Double.parseDouble(numberBean.getNum())) + "");
                        double mulF = CommonUtils.mul(0.01, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulF, Double.parseDouble(numberBean.getTimes())) + "");
                        setNowBound(nowBounds,numberBean);
                        break;
                    case R.id.deter:
                        numberBean.setModel("厘");
                        double mulL = CommonUtils.mul(0.001, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulL, Double.parseDouble(numberBean.getTimes())) + "");
                        numberBean.setPrice(CommonUtils.mul(0.01, Double.parseDouble(numberBean.getNum())) + "");
                        setNowBound(nowBounds,numberBean);
                        break;
                }
            }
        });

        ititBounds(mPoint, StringUtils.isEmpty(numberBean.getFd()) ? mPoint : numberBean.getFd(), nowBounds, mFD, mtvBuunds, numberBean);

        seekBar.setProgress(StringUtils.isEmpty(numberBean.getFd()) ? (float) Double.parseDouble(mPoint) : (float) Double.parseDouble(numberBean.getFd()));

        seekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

                ititBounds(mPoint, progressFloat + "", nowBounds, mFD, mtvBuunds, numberBean);
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

            }
        });

        number.setText(numberBean.getTimes());
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a = Integer.parseInt(number.getText().toString());
                a = a + 1;
                number.setText(a + "");
                numberBean.setTimes(a + "");
                double now = CommonUtils.mul(Double.parseDouble(numberBean.getSingelBouns()), a);
//                nowBounds.setText(now + "");
//                double mulL = CommonUtils.mul(0.001, Double.parseDouble(numberBean.getNum()));
//                numberBean.setAlltotal(CommonUtils.mul(a, Double.parseDouble(numberBean.getNum())) + "");
                switch (numberBean.getModel()) {
                    case "元":
                        double mulY = CommonUtils.mul(1, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulY, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                    case "角":
                        double mulJ = CommonUtils.mul(0.1, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulJ, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                    case "分":
                        double mulF = CommonUtils.mul(0.01, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulF, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                    case "厘":
                        double mulL = CommonUtils.mul(0.001, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulL, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                }
                setNowBound(nowBounds,numberBean);
            }
        });

        redButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a = Integer.parseInt(number.getText().toString());
                if (a == 1) {
                    numberBean.setTimes("1");
                } else {
                    a = a - 1;
                    numberBean.setTimes(a + "");
                }
                number.setText(a + "");
                double now = CommonUtils.mul(Double.parseDouble(numberBean.getSingelBouns()), a);
//                nowBounds.setText(now + "");
//                numberBean.setAlltotal(CommonUtils.mul(a, Double.parseDouble(numberBean.getNum())) + "");
                switch (numberBean.getModel()) {
                    case "元":
                        double mulY = CommonUtils.mul(1, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulY, Double.parseDouble(numberBean.getTimes())) + "");

                        break;
                    case "角":
                        double mulJ = CommonUtils.mul(0.1, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulJ, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                    case "分":
                        double mulF = CommonUtils.mul(0.01, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulF, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                    case "厘":
                        double mulL = CommonUtils.mul(0.001, Double.parseDouble(numberBean.getNum()));
                        numberBean.setAlltotal(CommonUtils.mul(mulL, Double.parseDouble(numberBean.getTimes())) + "");
                        break;
                }
                setNowBound(nowBounds,numberBean);
            }
        });
    }

    private void ititBounds(String point, String progress, TextView nowBounds, TextView mFD, TextView mtvBuunds, SelectNumberBean.NumberBean numberBean) {
        Log.i("D666", progress);
        float inum = (float) Double.parseDouble(point) - (float) Double.parseDouble(progress);
        DecimalFormat df1 = new DecimalFormat("0");// 格式化小数
        String s1 = df1.format(1700 + inum * 10 * 2);// 返回的是String类型
        mtvBuunds.setText(s1);
        mFD.setText(progress);
        numberBean.setFd(progress);
        numberBean.setPoint(progress);
        //最小+用户返点*20*系数
//        double du = CommonUtils.sub(Double.parseDouble(point), Double.parseDouble(progress));
//        double mul = CommonUtils.mul(20, du);
//        double mul2 = CommonUtils.mul(mul, Double.parseDouble(numberBean.getPos()));
//        double add = CommonUtils.add(Double.parseDouble(numberBean.getmMinPos()), mul2);
//
//        nowBounds.setText(add + "");
//
//        numberBean.setSingelBouns(add + "");
        setNowBound(nowBounds,numberBean);
    }

    public void setNowBound(TextView nowBounds, SelectNumberBean.NumberBean numberBean){
        double du = CommonUtils.sub(Double.parseDouble(mPoint), Double.parseDouble(numberBean.getPoint()));
        double mul = CommonUtils.mul(20, du);
        double mul2 = CommonUtils.mul(mul, Double.parseDouble(numberBean.getPos()));
        double add = CommonUtils.add(Double.parseDouble(numberBean.getmMinPos()), mul2);

        double times = Double.parseDouble(numberBean.getTimes());
        double model = 1;
        switch (numberBean.getModel()){
            case "元":
                model = 1;
                break;
            case "角":
                model = 0.1;
                break;
            case "分":
                model = 0.01;
                break;
            case "厘":
                model = 0.001;
                break;
        }

        double timeModel = CommonUtils.mul(times, model); //倍数*圆角模式
        double nowMoney = CommonUtils.mul(timeModel, add); //金钱数量
        nowBounds.setText(nowMoney + "");
        numberBean.setSingelBouns(nowMoney + "");
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.numberSelect:
                mSelectNumberList = new ArrayList<>();
                CommonUtils.setSelectNumberList(new Gson().toJson(mSelectNumberList));
                finish();
                break;
            case R.id.numberAww:
                mSelectNumberList = new ArrayList<>();
                CommonUtils.setSelectNumberList(new Gson().toJson(mSelectNumberList));
                EventBus.getDefault().post(new EventBusBean<String>("aww", "aww"));
                finish();
                break;
            case R.id.numberDelete:
                if (mSelectNumberList != null && mSelectNumberList.size() > 0) {
                    mSelectNumberList = new ArrayList<>();
                    mNumberCAdapter.setNewData(mSelectNumberList);
                    CommonUtils.setSelectNumberList(new Gson().toJson(mSelectNumberList));
                } else
                    showShortToast("没有选中号码~");
                break;
            case R.id.rlv_pursuenumber:
                lastlist = mSelectNumberList.subList(mSelectNumberList.size() - 1, mSelectNumberList.size());
                Gson gson = new Gson();
                String json = gson.toJson(lastlist);
                Bundle bundle = new Bundle();
                bundle.putString("pursuenumber", json);
                startActivity(PursueNumberActivity.class, bundle);
                finish();
                break;
            case R.id.betting:
                Gson gson1 = new Gson();
                String json1 = gson1.toJson(mSelectNumberList);
                ServerApi.setBettingData(json1)
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(@NonNull Disposable disposable) throws Exception {
                                startProgressDialog();
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<PurchaseDetailNumberBean>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {
                                stopProgressDialog();
                            }

                            @Override
                            public void onNext(@NonNull PurchaseDetailNumberBean numberBean) {
                                if (numberBean.getResult().equals("1")) {
                                    showShortToast(numberBean.getReturnval());
                                    CommonUtils.setSelectNumberList("");
                                    double money=0;
                                    for (int i=0;i<mSelectNumberList.size();i++){
                                        money+=Double.parseDouble( mSelectNumberList.get(i).getAlltotal());
                                    }
                                    Intent intent=new Intent(getApplicationContext(),BetSuccessActivity.class);
                                    intent.putExtra("strmoney",money+"");
                                    intent.putExtra("tag","0");
                                    startActivity(intent);
                                    finish();
                                } else {
                                    showShortToast(numberBean.getReturnval());
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                stopProgressDialog();

                            }

                            @Override
                            public void onComplete() {
                                stopProgressDialog();

                            }
                        });


                break;
        }
    }

}
